package com.chanjet.donkey.rest;

import java.net.URI;

import javax.servlet.http.HttpServletRequest;

import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.UriComponentsBuilder;
import org.springside.modules.web.MediaTypes;

@RestController
public abstract class BaseController<T> {

	@RequestMapping(method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
	public Page<T> index() {
		throw new UnsupportedOperationException();
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
	public T show(@PathVariable("id") Long id) {
		throw new UnsupportedOperationException();
	}
	
	@RequestMapping(method = RequestMethod.POST, consumes = MediaTypes.JSON)
	public ResponseEntity<?> create(@RequestBody T data, UriComponentsBuilder uriBuilder) {
		throw new UnsupportedOperationException();
	}
	
	
	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaTypes.JSON)
	// 按Restful风格约定，返回204状态码, 无内容. 也可以返回200状态码.
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void update(@RequestBody T data) {
		throw new UnsupportedOperationException();
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void delete(@PathVariable("id") Long id) {
		throw new UnsupportedOperationException();
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected ResponseEntity<?> redirect(String url, UriComponentsBuilder uriBuilder) {
		URI uri = uriBuilder.path(url).build().toUri();
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(uri);

		return new ResponseEntity(headers, HttpStatus.CREATED);
	}
	
	protected String param(String name, String v) {
		String value = getRequest().getParameter(name);
		return value == null ? v : value;
	}
	
	protected String param(String name) {
		return param(name, null);
	}
	
	protected int getPage() {
		String page = param("page", "1");
		return Integer.parseInt(page);
	}
	
	protected HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}
	
}
